package com.tian.arch.base

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.tian.arch.Foundation
import com.tian.arch.function.http.Resp
import com.tian.arch.function.http.check
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

open class BaseViewModel : ViewModel(), ILoadable {
    val loading = MutableLiveData<LoadingState>()

    override fun showLoading(message: String?) {
        loading.value = LoadingState.createLoading(message)
    }

    override fun hideLoading() {
        loading.value = LoadingState.createHide()
    }

    protected fun <T> launch(
        block: suspend () -> Resp<T>,
        success: (Resp<T>) -> Unit,
        failure: (Throwable) -> Unit = Foundation.globalConfig().errorHandler,
        finally: () -> Unit = {},
        showLoading: Boolean = false,
        loadingMsg: String? = null
    ): Job {
        return viewModelScope.launch {
            try {
                if (showLoading) showLoading(loadingMsg)
                val resp = block().check()
                success(resp)
            } catch (e: Throwable) {
                e.printStackTrace()
                failure(e)
            } finally {
                if (showLoading) hideLoading()
                finally()
            }
        }
    }
}